//
//  WebLoginViewController.m
//  zealcomm4.1Demo
//
//  Created by zealcomm user on 2019/11/27.
//  Copyright © 2019 zealcomm user. All rights reserved.
//

#import "WebLoginViewController.h"
#import <WebKit/WebKit.h>
@interface WebLoginViewController ()<WKScriptMessageHandler,WKUIDelegate,WKNavigationDelegate>
@property (weak, nonatomic) IBOutlet WKWebView *webview;

@property(strong,nonatomic)UIProgressView *progressView;

@end

@implementation WebLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initwebview];
    //创建
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 2)];
    
    //背景颜色
    self.progressView.backgroundColor = [UIColor grayColor];
    
    //样式
    self.progressView.progressViewStyle = UIProgressViewStyleDefault;
    
    //已完成进度颜色
    self.progressView.progressTintColor = [UIColor orangeColor];
    
    //现在的进度
    //_progressView.progress = 0.5;
    
    //动画
//    [UIView animateWithDuration:5 animations:^{
//        [progressView setProgress:0.8 animated:YES];
//    } completion:^(BOOL finished){
//        //NULL
//    }];
    
    //添加
    [self.view addSubview:self.progressView];
    
}

-(void)viewWillDisappear:(BOOL)animated{
   // [self.ivcsSdk send]
    [self.ivcsSdk sendMessageConfirmation:@{
        @"answer":@"ok",
        @"type":@"text",
        @"data":@""
    } toRoles:@"agents" onSuccess:^{
        NSLog(@"sendMessageConfirmation success");
    } onFailure:^(NSError * _Nonnull error) {
        NSLog(@"sendMessageConfirmation failed,%@",error);
    }];
}


-(void)initwebview{
    // UI代理
    _webview.UIDelegate = self;
    // 导航代理
    _webview.navigationDelegate = self;
    // 是否允许手势左滑返回上一级, 类似导航控制的左滑返回
    _webview.allowsBackForwardNavigationGestures = YES;
    //可返回的页面列表, 存储已打开过的网页
   // WKBackForwardList * backForwardList = [_webview backForwardList];
    
    // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.chinadaily.com.cn"]];
    //        [request addValue:[self readCurrentCookieWithDomain:@"http://www.chinadaily.com.cn"] forHTTPHeaderField:@"Cookie"];
    //        [_webview loadRequest:request];
    //页面后退
   // [_webview goBack];
    //页面前进
   // [_webview goForward];
    //刷新当前页面
  //  [_webview reload];
    
    //
    if([self.linkUrl rangeOfString:@"http://"].location==NSNotFound) {
          NSLog(@"不包含http://");
    }else{
        self.linkUrl = [self.linkUrl stringByReplacingOccurrencesOfString:@"http://" withString:@"https://"];
    }
    
    NSString *url = [self.linkUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSLog(@"%@",url);
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    //@"https://ivcs-demo.zealcomm.cn:3014/client"
    
    [_webview loadRequest:request];
    
    
    //添加监测网页加载进度的观察者
    [self.webview addObserver:self
                   forKeyPath:@"estimatedProgress"
                      options:0
                      context:nil];
    //添加监测网页标题title的观察者
    [self.webview addObserver:self
                   forKeyPath:@"title"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    
    
    //创建网页配置对象
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    
    // 创建设置对象
    WKPreferences *preference = [[WKPreferences alloc]init];
    //最小字体大小 当将javaScriptEnabled属性设置为NO时，可以看到明显的效果
    preference.minimumFontSize = 0;
    //设置是否支持javaScript 默认是支持的
    preference.javaScriptEnabled = YES;
    // 在iOS上默认为NO，表示是否允许不经过用户交互由javaScript自动打开窗口
    preference.javaScriptCanOpenWindowsAutomatically = YES;
    config.preferences = preference;
    
    // 是使用h5的视频播放器在线播放, 还是使用原生播放器全屏播放
    config.allowsInlineMediaPlayback = YES;
    //设置视频是否需要用户手动播放  设置为NO则会允许自动播放
    config.mediaTypesRequiringUserActionForPlayback = YES;
    //设置是否允许画中画技术 在特定设备上有效
    config.allowsPictureInPictureMediaPlayback = YES;
    //设置请求的User-Agent信息中应用程序名称 iOS9后可用
    config.applicationNameForUserAgent = @"ChinaDailyForiPad";
    //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
//    WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
    //这个类主要用来做native与JavaScript的交互管理
    WKUserContentController * wkUController = [[WKUserContentController alloc] init];
    //注册一个name为jsToOcNoPrams的js方法
   // [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"jsToOcNoPrams"];
   // [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"jsToOcWithPrams"];
    
    //WKScriptMessageHandler *handler = [WKScriptMessageH];
    
    [wkUController addScriptMessageHandler:self name:@"initsession"];
    [wkUController addScriptMessageHandler:self name:@"clientlogin"];
    config.userContentController = wkUController;
    
//    self.webview.configuration = config;
    
    

}

//通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
    //用message.body获得JS传出的参数体
    NSDictionary * parameter = message.body;
    //JS调用OC
    if([message.name isEqualToString:@"jsToOcNoPrams"]){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js调用到了oc" message:@"不带参数" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }])];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else if([message.name isEqualToString:@"jsToOcWithPrams"]){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js调用到了oc" message:parameter[@"params"] preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }])];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}



//kvo 监听进度 必须实现此方法
-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                      context:(void *)context{
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]
        && object == _webview) {
        NSLog(@"网页加载进度 = %f",_webview.estimatedProgress);
        self.progressView.progress = _webview.estimatedProgress;
        if (_webview.estimatedProgress >= 1.0f) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.progress = 0;
            });
        }
    }else if([keyPath isEqualToString:@"title"]
             && object == _webview){
        self.navigationItem.title = _webview.title;
    }else{
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
